package tailf

import (
	"fmt"
	"github.com/astaxie/beego/logs"
	"github.com/hpcloud/tail"
	"time"
)

type CollectConf struct {
	LogPath string
	Topic   string
}

type TailObj struct {
	tail *tail.Tail
	conf CollectConf
}

type TextMsg struct {
	Msg string
	Topic string
} 
type TailObjMgr struct {
	tailsobj []*TailObj
	msgChan chan *TextMsg
} 
var tailObjMgr *TailObjMgr

func GetOneLine()(msg *TextMsg)  {
	msg = <- tailObjMgr.msgChan
	return
}

func InitTail(c []CollectConf,chansize int) (err error) {
	if len(c) == 0 {
		err = fmt.Errorf("invalid config for log collect,conf:%v",c)
	}
	tailObjMgr = &TailObjMgr{
		msgChan:make(chan *TextMsg,chansize),
	}
	for _,v :=range c{
		obj := &TailObj{
			conf:v,
		}

		tails, errtail := tail.TailFile( v.LogPath, tail.Config{
			ReOpen: true,
			Follow: true,
			MustExist: false,
			Poll:      true,
		})
		if errtail != nil {
			err = errtail
			return
		}
		obj.tail = tails
		tailObjMgr.tailsobj = append(tailObjMgr.tailsobj,obj)
		
		go readFromTail(obj)
	}
	return
}

func readFromTail(tailobj *TailObj)  {
	for true {
		line,ok := <- tailobj.tail.Lines
		if !ok  {
			logs.Warn("ail file close reopen,filename:%s\n",tailobj.tail.Filename)
			time.Sleep(100 * time.Millisecond)
			continue
		}
		textmsg := &TextMsg{Msg:line.Text,Topic:tailobj.conf.Topic}

		tailObjMgr.msgChan <- textmsg
	}
}
